package pers.sloera.leetcode.editor.cn;

import java.util.HashMap;
import java.util.Map;

/**
 * TinyURL 的加密与解密
 * @author sloera
 * @date 2022-06-29 21:35:35
 */
class EncodeAndDecodeTinyurl {
    public static void main(String[] args) {
        EncodeAndDecodeTinyurl solution = new EncodeAndDecodeTinyurl();
        Codec codec = solution.new Codec();
        System.out.println(codec.decode(codec.encode("https://leetcode.cn/problems/encode-and-decode-tinyurl/")));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    public class Codec {

        // 保存映射关系
        Map<String, String> map = new HashMap<>();
        String[] VALID_CHAR = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            char[] chars = longUrl.toCharArray();
            int[] resultIndex = new int[6];
            int step = chars.length / resultIndex.length;
            for (int i = 0; i < resultIndex.length; i++) {
                for (int j = i * step; j < chars.length && j < (i + 1) * step; j++) {
                    resultIndex[i] = (resultIndex[i] + chars[j]) % VALID_CHAR.length;
                }
            }
            StringBuilder stringBuilder = new StringBuilder();
            for (int index : resultIndex) {
                stringBuilder.append(VALID_CHAR[index]);
            }
            map.put(stringBuilder.toString(), longUrl);
            return stringBuilder.toString();
        }

        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            return map.get(shortUrl);
        }
    }

    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.decode(codec.encode(url));
    //leetcode submit region end(Prohibit modification and deletion)

}
